package com.mactivity.activities;

import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Spannable;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mactivity.database.LoginFunctions;
import com.mactivity.helper.Constants;
import com.mactivity.helper.EncryptionHelper;
import com.mactivity.helper.Messages;
import com.mactivity.helper.SharedPreferenceHelper;
import com.mactivity.helper.ValidationsHelper;

/**
 * This class contains all the UI components of the Login Activity and handlers
 * of all the events that occur on such activities.
 * 
 * @author Shwetha Narayan
 * 
 */
public class LoginActivity extends Activity implements OnClickListener {
	EditText editEmailId;
	EditText editPassword;
	Button buttonLogin;
	Button buttonRegister;
	TextView textForgotPassword;
	SharedPreferenceHelper preferenceHelper;

	public static final int INVALID_LOGIN = 10;

	/**
	 * This method is created on the creation of the activity. It creates the
	 * instances of the different components present on the screen and assigns
	 * the handlers to them.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());

		// Find the details in the shared Preferences, to find if the user has
		// logged in or not
		preferenceHelper = new SharedPreferenceHelper(this);
		SharedPreferences settings = preferenceHelper
				.getSharedPreferenceSetting();
		boolean loggedIn = settings.getBoolean("loggedIn", false);

		Log.d(Constants.LOG_LOGIN_TAG,
				"Shared Preference(User logged in previously): " + loggedIn);

		if (loggedIn) {
			Log.d(Constants.LOG_LOGIN_TAG, "Moving into home screen ");
			Intent myIntent = new Intent(LoginActivity.this, HomeActivity.class);
			LoginActivity.this.startActivity(myIntent);
			LoginActivity.this.finish();

		} else {

			super.onCreate(savedInstanceState);
			setContentView(R.layout.main);
		}
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// User Name and Password
		editEmailId = (EditText) findViewById(R.id.editEmailId);
		editPassword = (EditText) findViewById(R.id.editPassword);

		// BUttons
		buttonLogin = (Button) findViewById(R.id.buttonLogin);
		buttonRegister = (Button) findViewById(R.id.buttonRegister);

		// On click on login, authenticate the user and login to the home page.
		buttonLogin.setOnClickListener(this);

		// On click on register, navigate to registration page.
		buttonRegister.setOnClickListener(this);

		// Forgot Password link
		textForgotPassword = (TextView) findViewById(R.id.textForgotPassword);
		textForgotPassword.setMovementMethod(LinkMovementMethod.getInstance());

		Spannable spans = (Spannable) textForgotPassword.getText();
		ClickableSpan clickSpan = new ClickableSpan() {

			@Override
			public void onClick(View widget) {
				// Create the Forgot Password page
				Intent myIntent = new Intent(LoginActivity.this,
						ForgotPasswordActivity.class);
				LoginActivity.this.startActivity(myIntent);
				finish();
			}
		};
		spans.setSpan(clickSpan, 0, spans.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
	}

	/**
	 * Handles the onClick events triggered on the buttons, this is done by
	 * implementing the onClickListners onClick method to suite the application
	 * need.
	 */
	public void onClick(View v) {
		// Check for which button was clicked
		switch (v.getId()) {
		case R.id.buttonLogin:
			// Logging login details
			String emailId = editEmailId.getText().toString();
			String password = editPassword.getText().toString();

			Log.d(Constants.LOG_LOGIN_TAG, "Onclick of Login: Email Id: "
					+ emailId + " Password :" + password);

			// Check if the email Id password are empty
			if (emailId.trim().isEmpty() || password.trim().isEmpty()) {
				Toast.makeText(this, Messages.EMAIL_PASSWORD_EMPTY,
						Toast.LENGTH_SHORT).show();
			}

			// Check the email id pattern
			// Pattern foe email syntax matching
			boolean emailMatch = ValidationsHelper.checkEmailFormat(emailId);

			if (emailMatch) {
				LoginFunctions loginFunctions = new LoginFunctions();
				String result = loginFunctions.userLogin(emailId, EncryptionHelper.encrypt(password));

				if (result == null) {
					showDialog(INVALID_LOGIN);
				} else {

					// Parse the details in the json returned from the database
					Map<String, String> userDetails = loginFunctions
							.getUserDetails(result);

					// On successful Login change the State in the Shared
					// Preferences
					SharedPreferences settings = preferenceHelper
							.getSharedPreferenceSetting();
					SharedPreferences.Editor editor = settings.edit();
					editor.putBoolean(Constants.IS_LOGGED_IN, true);
					editor.putInt(Constants.USER_ID,
							Integer.valueOf(userDetails.get(Constants.USER_ID)));
					editor.putString(Constants.USER_NAME,
							userDetails.get(Constants.USER_NAME));
					editor.putString(Constants.USER_EMAIL_ID,
							userDetails.get(Constants.USER_EMAIL_ID));

					// Commit the edits!
					editor.commit();

					// Clear the password field
					editPassword.setText("");

					// Start the new activity
					Intent myIntent = new Intent(LoginActivity.this,
							HomeActivity.class);
					LoginActivity.this.startActivity(myIntent);
					finish();
				}
			} else {
				// If the format of the password is wrong, display it to user.
				Toast.makeText(this, Messages.INVALID_EMAIL_FORMAT,
						Toast.LENGTH_SHORT).show();
			}

			break;

		case R.id.buttonRegister:
			Intent myIntent = new Intent(LoginActivity.this,
					RegisterActivity.class);
			LoginActivity.this.startActivity(myIntent);
			finish();
			break;
		}
	}

	/**
	 * Creates the dialog box for the user, showing the invalid login case to
	 * the user with a message.
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case INVALID_LOGIN:
			// Create out AlterDialog
			Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(Messages.EMAIL_PASSWORD_INVALID);
			builder.setCancelable(true);
			builder.setNegativeButton("Dismiss", new CancelOnClickListener());
			AlertDialog dialog = builder.create();
			dialog.show();
		}
		return super.onCreateDialog(id);
	}

	/**
	 * Implement the CancelOnClickListner, so that the button can take you to
	 * the same page. This is used by the dismiss button of the pop up.
	 */
	private class CancelOnClickListener implements
			DialogInterface.OnClickListener {
		public void onClick(DialogInterface dialog, int which) {
			// Do nothing, as it goes back to login screen
		}
	}

}